import { GetterTree, ActionTree, MutationTree } from 'vuex'
import { RootState } from '~/store'
import $cookies from '~/utils/cookie'

export const state = () => ({
    tokenVal: ''
})

export type UserModuleState = ReturnType<typeof state>

export const mutations: MutationTree<UserModuleState> = {
    UPDATE_TOKEN(state, payload: string) {
        state.tokenVal = payload
    }
}

export const getters: GetterTree<UserModuleState, RootState> = {
    isLogin: (state) => !!state.tokenVal,
    tokenKey: (state, getters, rootState) => rootState.tokenKey
}

export const actions: ActionTree<UserModuleState, RootState> = {
    login({ commit, rootState }, token) {
        commit('UPDATE_TOKEN', token)
        $cookies.set(rootState.tokenKey, token, {
            maxAge: 60 * 60 * 24 * 7,
            path: '/'
        })
    },
    logout({ commit, rootState }) {
        commit('UPDATE_TOKEN', '')
        $cookies.remove(rootState.tokenKey)
    }
}
